namespace SimpleWebServices.Web
{
    using System;
    using System.Configuration;
    using System.Net;
    using System.Web;
    using Moq;
    using SimpleWebServices;
    using SimpleWebServices.Configuration;
    using Xunit;

    public sealed class UriRedirectionModuleFacts
    {
        [Fact]
        public void typedef()
        {
            Assert.True(new ObjectExpectations<UriRedirectionModule>()
                .DerivesFrom<object>()
                .IsConcreteClass()
                .IsSealed()
                .HasDefaultConstructor()
                .Implements<IHttpModule>()
                .Result);
        }

        [Fact]
        public void ctor()
        {
            Assert.NotNull(new UriRedirectionModule());
        }

        [Fact]
        public void op_Dispose()
        {
            new UriRedirectionModule().Dispose();
        }

        [Fact]
        public void op_Init_HttpApplication()
        {
            new UriRedirectionModule().Init(new Mock<HttpApplication>().Object);
        }

        [Fact]
        public void op_Init_HttpApplicationNull()
        {
            Assert.Throws<ArgumentNullException>(() => new UriRedirectionModule().Init(null as HttpApplication));
        }

        [Fact]
        public void op_OnBeginRequest_object_EventArgs()
        {
            ConfigurationManager.RefreshSection("simplewebservices/redirection");

            try
            {
                RedirectionConfiguration.Settings().Uri.Add(new RedirectionSetting
                {
                    From = "http://www.example.com/abc",
                    To = "https://www.example.net/xyz"
                });

                var mock = new Mock<HttpContextBase>();
                mock.SetupGet<Uri>(x => x.Request.Url).Returns(new Uri("http://www.example.com/abc")).Verifiable();
                mock.SetupSet(x => x.Response.StatusCode).Callback(actual => Assert.Equal<int>(actual, (int)HttpStatusCode.SeeOther)).Verifiable();
                mock.Setup(x => x.Response.AppendHeader("Location", "https://www.example.net/xyz")).Verifiable();
                mock.Setup(x => x.Response.Cache.SetCacheability(HttpCacheability.Server)).Verifiable();
                mock.Setup(x => x.Response.Cache.SetExpires(It.IsAny<DateTime>())).Verifiable();
                mock.Setup(x => x.Response.End()).Verifiable();
                HttpContextFactory.Mock = mock.Object;

                new UriRedirectionModule().OnBeginRequest(null as object, EventArgs.Empty);

                mock.VerifyAll();
            }
            finally
            {
                ConfigurationManager.RefreshSection("simplewebservices/redirection");
                HttpContextFactory.Reset();
            }
        }
    }
}